package org.itboys.weixin.tools;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.itboys.commons.utils.json.JsonUtils;
import org.itboys.weixin.constant.WeixinConstants;
import org.itboys.weixin.dto.AccessToken;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.google.common.collect.Maps;

/**
 * 微信相关
 * @author ChenJunhui
 *
 */
public class WeixinUtils {

	/**
	 * 用于暂存accessToken的map key为微信appId 会有定时线程定时清除的
	 */
	private static final Map<String, String> accessTokenMap = new HashMap<String, String>();
	private static Timer timer = null;
	
	/**
	 * 密钥交换token
	 * @param appId
	 * @return
	 */
	public static String getAccessToken(String appId, String appSecret) {
		String accessToken = accessTokenMap.get(appId);
		if(accessToken!=null){
			return accessToken;
		}
		return fetchAccessTokenAndSetToMap(appId, appSecret);
	}
	
	/**
	 * 清除存在MAP中的缓存
	 * @param appId
	 */
	public static void cleanAccessToken(String appId){
		accessTokenMap.remove(appId);
	}
	
	/**
	 * 重新设置缓存中的token
	 * @param appId
	 * @param token
	 */
	public static void reSetAccessToken(String appId, String token){
		accessTokenMap.put(appId, token);
	}

	/**
	 * 取得token并放入变量里
	 * @param appId
	 * @param appScret
	 * @return
	 */
	private static synchronized String fetchAccessTokenAndSetToMap(String appId,String appScret) {
		String accessToken = accessTokenMap.get(appId);
		if(accessToken!=null){
			return accessToken;
		}
		String url=WeixinConstants.URL.FETCH_TOKEN_URL+"&appid="+appId+"&secret="+appScret;
		String jsonToken = HttpHelper.doGet(url);
		AccessToken token = JsonUtils.jsonToObject(AccessToken.class, jsonToken);
		accessToken = token.getAccess_token();
		accessTokenMap.put(appId, accessToken);
		if(timer==null){
			timer = new Timer();
		}
		long delay = token.getExpires_in();
		if(delay>50){//其实有7200秒的有效时间 不知道有效时间会不会变 反正提前50秒去清空本地map的accessToken 
			delay=delay-50;
		}
		timer.schedule(new ClearAccessTokenTask(appId), delay*1000);
		return accessToken;
	}
	
	static class ClearAccessTokenTask extends TimerTask{
		private String appId;
		public ClearAccessTokenTask(String appId){
			this.appId=appId;
		}
		@Override
		public void run() {
			synchronized (accessTokenMap) {
				accessTokenMap.remove(appId);
			}
		}
	}
	
	/**
	 * 获取生成二维码用的ticket
	 * @param action_name ： 二维码类型  QR_SCENE:临时二维码    QR_LIMIT_SCENE:永久二维码
	 * @param paramId : 参数ID
	 * @return
	 */
	public static String getTicket(String access_token, String action_name, Long paramId){
       try {
   		   Map<String, Object> param = Maps.newHashMapWithExpectedSize(3);
           param.put("expire_seconds", 604800);
           param.put("action_name", action_name);
           
           Map<String, Object> param2 = Maps.newHashMapWithExpectedSize(1);
           Map<String, Object> param3 = Maps.newHashMapWithExpectedSize(1);
           param3.put("scene_id", paramId);
           param2.put("scene", param3);
           param.put("action_info", param2);
           
           String result = HttpHelper.doJsonParamPost(WeixinConstants.URL.GET_TOWCODE_TICKET+access_token, JSON.toJSONString(param));
           return (String) JSON.parseObject(result).get("ticket");
		} catch (JSONException e) {
			e.printStackTrace();
		}
       return null;
	}
	
}
